package com.goods.business.service.imp;

import com.auth0.jwt.JWTVerifier;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.goods.business.mapper.*;
import com.goods.business.service.InStockService;
import com.goods.common.error.BusinessCodeEnum;
import com.goods.common.error.BusinessException;
import com.goods.common.model.business.*;
import com.goods.common.utils.JWTUtils;
import com.goods.common.vo.business.InStockDetailVO;
import com.goods.common.vo.business.InStockItemVO;
import com.goods.common.vo.business.InStockVO;
import com.goods.common.vo.business.SupplierVO;
import com.goods.common.vo.system.PageVO;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: Mr.Cao
 * @DateTime: 2021/11/10 0:42
 * BMW F750GS
 **/
@Service
public class InStockServiceImpl implements InStockService {
    @Autowired
    private InStockMapper inStockMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private InStockInfoMapper inStockInfoMapper;
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private ProductStockMapper productStockMapper;
    /**
     * 分页查询入库记录
     * */
    @Override
    public PageVO findInStockList(Map queryMap) {
        String pageNum = (String) queryMap.get("pageNum");
        String pageSize = (String) queryMap.get("pageSize");
        //分页
        Page<Object> page = PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        //条件查询
        Example o = new Example(InStock.class);
        Example.Criteria criteria = o.createCriteria();
        //状态 例如:已入库,回收站
        String status = (String) queryMap.get("status");
        criteria.andEqualTo("status",status);
        //类型 例如:捐赠,下拨,采购,借用
        String type = (String) queryMap.get("type");
        if (!StringUtils.isEmpty(type)){
            criteria.andEqualTo("type",type);
        }
        //单号
        String inNum = (String) queryMap.get("inNum");
        if (!StringUtils.isEmpty(inNum)){
            criteria.andLike("inNum",inNum);
        }
        //日期: 开始日期和结束日期
        String startTime = (String) queryMap.get("startTime");
        String endTime = (String) queryMap.get("endTime");
        if (!StringUtils.isEmpty(startTime)&&!StringUtils.isEmpty(endTime)){
            criteria.andGreaterThanOrEqualTo("createTime",startTime);//大于等于
            criteria.andLessThanOrEqualTo("createTime",endTime);//小于等于
        }


        List<InStock> inStocks = inStockMapper.selectByExample(o);
        //System.out.println("inStocks = " + inStocks);
        //转换Vo
        List<InStockVO> inStockVOList = inStocks.stream().map(inStock -> {
            InStockVO inStockVO = new InStockVO();
            Supplier supplier = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());
            BeanUtils.copyProperties(inStock, inStockVO);
            //设置联系方式和提供方名称
            inStockVO.setPhone(supplier.getPhone());
            inStockVO.setSupplierName(supplier.getName());
            return inStockVO;
        }).collect(Collectors.toList());

        return new PageVO(page.getTotal(),inStockVOList);
    }
    /**
     * 新建入库记录
     * */
    @Transactional
    @Override
    public void addIntoStock(InStockVO inStockVO, HttpServletRequest request) {
        //如果是未知物资来源,保存物资来源
        if (inStockVO.getSupplierId()==null||inStockVO.getSupplierId()==0){
            //未知物资来源
            Supplier supplier = new Supplier();
            supplier.setName(inStockVO.getName());
            supplier.setAddress(inStockVO.getAddress());
            supplier.setEmail(inStockVO.getEmail());
            supplier.setPhone(inStockVO.getPhone());
            supplier.setCreateTime(new Date());
            supplier.setModifiedTime(new Date());
            supplier.setSort(inStockVO.getSort());
            supplier.setContact(inStockVO.getContact());
            //保存到DB
            supplierMapper.insert(supplier);
            //主键回填
            inStockVO.setSupplierId(supplier.getId());
        }

        //随机生成入库单号
        String iNum = UUID.randomUUID().toString().replace("-", "");
        inStockVO.setInNum(iNum);

        //保存物资物资明细,包括 物资名称,数量等
        List<Map> products = inStockVO.getProducts();
        int productTotal = 0;//记录商品总数量
        if (!CollectionUtils.isEmpty(products)){
            for (Map product : products) {
                //封装商品清单信息
                InStockInfo inStockInfo = new InStockInfo();
                inStockInfo.setInNum(iNum);
                //查询pNum 根据productId
                Integer productId = (Integer) product.get("productId");
                Product productById = productMapper.selectByPrimaryKey(productId);
                inStockInfo.setPNum(productById.getPNum());
                Integer productNumber = (Integer) product.get("productNumber");
                inStockInfo.setProductNumber(productNumber);
                //创建和修改时间
                inStockInfo.setCreateTime(new Date());
                inStockInfo.setModifiedTime(new Date());


                //保存到DB
                inStockInfoMapper.insert(inStockInfo);
                productTotal+=productNumber;
            }
        }

        //进行入库单新增记
        //添加和修改时间
        inStockVO.setCreateTime(new Date());
        inStockVO.setModified(new Date());
        //添加商品总数量
        inStockVO.setProductNumber(productTotal);
        //获取操作员名称
        String authorization = request.getHeader("Authorization");
        String username = JWTUtils.getUsername(authorization);
        inStockVO.setOperator(username);
        inStockVO.setStatus(2);//状态默认为待审核
        //类型转换
        InStock inStock = new InStock();
        BeanUtils.copyProperties(inStockVO,inStock);
        inStockMapper.insert(inStock);
    }
    /**
     * 查看入库记录明细
     * */
    @Override
    public InStockDetailVO detail(long id, Integer pageNum) {

        InStockDetailVO inStockDetailVO = new InStockDetailVO();

        //查询入库记录明细主表
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        //转换Vo
        BeanUtils.copyProperties(inStock,inStockDetailVO);

        //查询入库来源表
        Supplier supplier = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());
        //转换Vo
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier,supplierVO);
        inStockDetailVO.setSupplierVO(supplierVO);


        //查询入库的商品集合
        //先查询inStockInfo表，查询出商品集合
        Example o = new Example(InStockInfo.class);
        o.createCriteria().andEqualTo("inNum",inStock.getInNum());
        //分页查询
        Page<Object> page = PageHelper.startPage(pageNum, 5);
        List<InStockInfo> inStockInfos = inStockInfoMapper.selectByExample(o);
        //查询对应的商品
        for (InStockInfo inStockInfo : inStockInfos) {
            Example productExample = new Example(Product.class);
            productExample.createCriteria().andEqualTo("pNum", inStockInfo.getPNum());
            Product productByPNum = productMapper.selectOneByExample(productExample);
            //转换Vo
            InStockItemVO inStockItemVO = new InStockItemVO();
            BeanUtils.copyProperties(productByPNum, inStockItemVO);
            inStockItemVO.setCount(inStockInfo.getProductNumber());
            //添加到最后的Vo中
            inStockDetailVO.getItemVOS().add(inStockItemVO);
        }
        inStockDetailVO.setTotal(page.getTotal());
        return inStockDetailVO;
    }
    /**
     * 审核通过,并更新库存表
     * */
    @Transactional
    @Override
    public void publish(long id) throws BusinessException {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        if (inStock!=null){
            inStock.setStatus(0);//设置状态为 正常
            //更新状态
            inStockMapper.updateByPrimaryKey(inStock);
            //查询商品集合 根据inNum
            Example exampleInStockInfo = new Example(InStockInfo.class);
            exampleInStockInfo.createCriteria().andEqualTo("inNum",inStock.getInNum());
            List<InStockInfo> inStockInfos = inStockInfoMapper.selectByExample(exampleInStockInfo);
            for (InStockInfo inStockInfo : inStockInfos) {
                //更新商品库存
                //先查询商品库存,根据Pnum
                Example exampleProductStock = new Example(ProductStock.class);
                exampleProductStock.createCriteria().andEqualTo("pNum",inStockInfo.getPNum());
                ProductStock productStock = productStockMapper.selectOneByExample(exampleProductStock);
                if (productStock!=null){//有库存记录
                    //更新库存
                    productStock.setStock(inStockInfo.getProductNumber()+productStock.getStock());
                    productStockMapper.updateByPrimaryKey(productStock);
                }else {//没有库存记录
                    //新增库存表
                    productStock = new ProductStock();
                    productStock.setPNum(inStockInfo.getPNum());
                    productStock.setStock(inStockInfo.getProductNumber().longValue());
                    productStockMapper.insert(productStock);
                }
            }


        }
    }
    /**
     * 审核不通过, 删除, 并更新库存表
     * */
    @Override
    public void delete(long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        if (inStock!=null){
            inStockMapper.deleteByPrimaryKey(id);
        }
    }
    /**
     * 移除进入回收站
     * */
    @Override
    public void remove(long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        if (inStock!=null){
            inStock.setStatus(1);//设置状态为 回收站
            inStockMapper.updateByPrimaryKey(inStock);
        }
    }
    /**
     * 还原: 恢复到正常
     * */
    @Override
    public void back(long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        if (inStock!=null&&inStock.getStatus().equals(1)){
            inStock.setStatus(0);//设置状态为 回收站
            inStockMapper.updateByPrimaryKey(inStock);
        }
    }
}
